<script setup>
import { Icon } from '@iconify/vue';
import dayjs from 'dayjs';
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import useStore from "@/store/index.js";
import { useRouter } from 'vue-router'
import { getFirendList, getOnLineList, getMessageList, getSystemMsg } from '@/api/user'
const router = useRouter()
const { userInfo } = useStore()
const friendList = ref([])
const onLineLit = ref([])
const records = ref([])
const systemList = ref([])
const loadGetFriendList = async () => {
	const res = await getFirendList(userInfo.userInfo.id)
	friendList.value = res.data
	await loadOnline()
	getUserLastMsg()
}
loadGetFriendList()

// 获取在线用户
const loadOnline = async () => {
	const res = await getOnLineList()
	onLineLit.value = res.data
	friendList.value.forEach(item => {
		onLineLit.value.includes((item.id).toString()) ? item.onLine = true : item.onLine = false
	})
}

//获取每个用户的最后一条消息列表
const getUserLastMsg = async () => {
	await Promise.all(
		friendList.value.map(async (item) => {
			let num = 0
			const res = await getMessageList({ friendId: item.id, userId: userInfo.userInfo.id });
			res.data.forEach(e => {
				if (e.isRead == "1" && e.senderId != userInfo.userInfo.id) {
					num++
				}
			})
			item.message = res.data.length ? res.data[res.data.length - 1].content : "";
			item.isRead = res.data.length ? res.data[res.data.length - 1].isRead : "2";
			item.readNum = num
			item.createdTime = res.data.length ? res.data[res.data.length - 1].createdTime : Date.now();
		})
	);
	records.value = [...friendList.value.filter(item => item.message), ...systemList.value].sort((a, b) => {
		return b.createdTime - a.createdTime
	})
	console.log("消息", records.value)
};

// 获取系统消息
const getSystemMsgList = async () => {
	const res = await getSystemMsg({ page: 1, pageSize: 100 })
	// 用于存储不同类型的最新消息
	const latestMessages = {};
	// 遍历消息数组
	res.data.records.filter(item => item.revocation == 1).forEach(msg => {
		// 如果该类型不存在或当前消息更新，则更新
		if (!latestMessages[msg.type] || latestMessages[msg.type].id < msg.id) {
			latestMessages[msg.type] = msg;
		}
	});
	// 获取前四个不同类型的消息
	const result = Object.values(latestMessages)
		.slice(0, 4) // 只取最多四个
		.filter((item, index, self) =>
			index === self.findIndex((t) => (
				t.type === item.type
			))
		);
	systemList.value = result
}
getSystemMsgList()


// 聊天功能
const goChat = (item) => {
	if (item.type) {
		router.push(`/notice?type=${item.type}`)
	} else {
		localStorage.setItem("friendInfo", JSON.stringify(item))
		router.push("/chat")
	}
}
// 创建WebSocket对象
userInfo.webSocket = new WebSocket(`ws://192.168.110.16:8083/chat/${userInfo.userInfo.id}`)
let localReco = true
// 接受websocket推送消息,获取好友在线列表
userInfo.webSocket.onmessage = (e) => {
	let response = JSON.parse(e.data)
	console.log(response)
	if (response && response.code == "1") {
		const index = records.value.findIndex(item => item.id == response.fromName)
		if (index != -1) {
			records.value[index].message = response.message
			records.value[index].isRead = "1"
			if (localReco) {
				records.value[index].readNum = 1
				localReco = false
			} else {
				records.value[index].readNum++
			}
		} else {
			const obj = friendList.value.find(item => item.id == response.fromName)
			obj.message = response.message
			obj.readNum = 1
			obj.isRead = "1"
			records.value.push(obj)
			console.log("shujuzhong", obj)
		}
	} else if (response.system) {
		const index = records.value.findIndex(item => item.type == response.message.type);
		records.value.splice(index, 1);
		records.value.unshift(response.message)
	} else {
		loadOnline()
	}
}

</script>

<template>
	<!-- 导航栏 -->
	<van-nav-bar :style="{ background: '#151515' }" :border="false" fixed>
		<template #title>
			<Icon icon="tabler:camera-selfie" class="text-[#fff]" />
		</template>
		<template #left>
			<Icon icon="formkit:add" class="text-[#fff]" />
		</template>
		<template #right>
			<Icon icon="tabler:search" class="text-[#fff]" />
		</template>
	</van-nav-bar>
	<!-- 主体内容 -->
	<div class="main bg-[#151515] pt-[56px] px-[10px]">
		<!-- 朋友在线 -->
		<div class="scroll-container" v-if="friendList.length">
			<div class="w-[70px] h-[70px] flex flex-col items-center" style="min-width: 70px" v-for="item in friendList"
				:key="item.id" @click="goChat(item)">
				<div class="relative mb-[10px]" :class="{ 'online': item.onLine }">
					<img :src="item.avatar" class="w-[70px] h-[70px] rounded-[50%]" />
				</div>
				<span class="text-[12px]">{{ item.nickname }}</span>
			</div>
		</div>
		<!-- 消息 列表-->
		<div class="px-[10px]">
			<!-- 新朋友 -->
			<div class="flex items-center">
				<img src="@/assets/msg-icon1.png" class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" />
				<div class="flex-1 py-[15px]">
					<span class="text-[16px] text-[#fff] flex items-start">新朋友</span>
					<span class="text-[14px] mt-[4px] felx items-center text-[#a2a2a3]">xxx 关注了你</span>
				</div>
				<div class="w-[15px]"><van-icon name="arrow" color="#797979" /></div>
			</div>
			<!-- 互动消息 -->
			<div class="flex items-center">
				<img src="@/assets/msg-icon2.png" class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" />
				<div class="flex-1 py-[15px]">
					<span class="text-[16px] text-[#fff] flex items-start">互动消息 </span>
					<span class="text-[14px] mt-[4px] felx items-center text-[#a2a2a3]">xxx 近期访问过你的主页</span>
				</div>
				<div class="w-[15px]"><van-icon name="arrow" color="#797979" /></div>
			</div>
			<!-- 好友及系统消息 -->
			<div class="flex items-center" v-for="item in records" :key="item" @click="goChat(item)">
				<img src="https://dy.ttentau.top/assets/msg-icon4-vDykjBaw.png"
					class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" v-if="item.type == 1" />
				<img src="@/assets/qb.webp" class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" v-else-if="item.type == 2" />
				<img src="@/assets/zb.webp" class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" v-else-if="item.type == 3" />
				<img src="https://dy.ttentau.top/assets/msg-icon5-CT2-p36i.webp"
					class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" v-else-if="item.type == 4" />
				<img :src="item.avatar" class="mr-[15px] w-[55px] h-[55px] rounded-[50%]" v-else />
				<div class="flex-1 py-[15px]">
					<span class="text-[16px] text-[#fff] flex items-start" v-if="item.type == 1">系统消息</span>
					<span class="text-[16px] text-[#fff] flex items-start" v-if="item.type == 2">钱包通知</span>
					<span class="text-[16px] text-[#fff] flex items-start" v-if="item.type == 3">直播消息</span>
					<span class="text-[16px] text-[#fff] flex items-start" v-if="item.type == 4">抖音小助手</span>
					<span class="text-[16px] text-[#fff] flex items-start" v-if="!item.type">{{ item.nickname }}</span>
					<span class="text-[14px] mt-[4px] felx items-center text-[#a2a2a3] " v-if="item.type"> {{ item.title }} ·
						{{ dayjs(item.createdTime).format("MM-DD HH:mm") }} </span>
					<span class="text-[14px] mt-[4px] felx items-center text-[#a2a2a3] " v-else> {{ item.message }} ·
						{{ dayjs(item.createdTime).format("MM-DD HH:mm") }} </span>
				</div>
				<div class="w-[30px]">
					<van-badge :content="item.readNum" max="99" v-if="item.isRead == 1 && item.readNum && !item.type" />
					<van-badge v-if="item.type && item.isRead == 1" dot />
				</div>
			</div>
			<!-- 到底提醒 -->
			<div class="text-[#959596] text-center py-[25px]">
				暂时没有更多了
			</div>
		</div>
	</div>
</template>

<style scoped lang="scss">
:deep(.van-nav-bar__left),
:deep(.van-nav-bar__right) {
	font-size: 23px !important;
}

:deep(.van-nav-bar__title) {
	font-size: 26px !important;
}

.main {
	min-height: calc(100vh - 60px);
}

.scroll-container {
	display: flex;
	gap: 20px;
	height: 100px;
	overflow-x: scroll;
}

.scroll-container::-webkit-scrollbar {
	display: none;
}

.online::before {
	content: ' ';
	border: 4px solid black;
	width: 20px;
	height: 20px;
	background: rgb(115, 254, 73);
	border-radius: 50%;
	position: absolute;
	bottom: 0;
	right: 0;
}
</style>
